//app.js
App({
  onLaunch: function (e) {
    console.log(e)
    if(e.query.vendorUserId){
      //wx.setStorageSync('vendorUserId',e.query.vendorUserId);
      this.globalData.vendorUserId = e.query.vendorUserId;
    }
    if(e.query.prodId){
      //wx.setStorageSync('vendorUserId',e.query.vendorUserId);
      this.globalData.prodId = e.query.prodId;
    }
    if(e.query.companyId){
      //wx.setStorageSync('vendorUserId',e.query.vendorUserId);
      this.globalData.companyId = e.query.companyId;
    }
    var session_key;
    if(session_key = wx.getStorageSync('session_key')){
      this.globalData.session_key = session_key;
    }
    //this.checkLogin();
  },
  onShow: function(){
  },
  onHide: function(){
  },
  sendRequest: function(param, customSiteUrl){
    var that = this,
        data = param.data || {},
        header = param.header,
        requestUrl;  
    // data._app_id = this.getAppId();
    // data.app_id = this.getAppId();
    // if(!this.globalData.notBindXcxAppId){
    //   data.session_key = this.getSessionKey();
    // }

    if(customSiteUrl) {
      requestUrl = customSiteUrl + param.url;
    } else {
      requestUrl = this. globalData.siteBaseUrl + param.url;
    }

    if(param.method){
      if(param.method.toLowerCase() == 'post'){
        //data = this.modifyPostParam(data);
        header = header || {
          'content-type': 'application/x-www-form-urlencoded;'
        }
      }
      param.method = param.method.toUpperCase();
    }

    this.showToast({
      title: '请求中...',
      icon: 'loading'
    });
    wx.request({
      url: requestUrl,
      data: data,
      method: param.method || 'GET',
      header: header || {
        'content-type': 'application/json'
      },
      success: function(res) {
        if(res.statusCode && res.statusCode != 200){
          that.hideToast();
          that.showModal({
            content: ''+res.errMsg
          });
          return;
        }
        if(res.data.status){
          if(res.data.status == 401){
            that.login();
            return;
          }
          if(res.data.status != 0){
            that.hideToast();
            that.showModal({
              content: ''+res.data.data
            });
            return;
          }
        }
        typeof param.success == 'function' && param.success(res.data);
      },
      fail: function(res){
        that.showModal({
          content: '请求失败 '+res.errMsg
        })
        typeof param.fail == 'function' && param.fail(res.data);
      },
      complete: function(res){
        typeof param.complete == 'function' && param.complete(res.data);
      }
    });
  },
  login: function(){
    var that =this;
    var login_data={};
    wx.login({
      success: function (data) {
         login_data.wxCode = data.code;
          wx.getUserInfo({
            success: function (res) {
              var userInfo = res.userInfo;  
              login_data.avatarUrl = userInfo.avatarUrl;
              login_data.nickName = userInfo.nickName;
              login_data.gender = userInfo.gender;
              login_data.province = userInfo.province;
              login_data.city = userInfo.city;
              that.sendCode(login_data);
            }
          })
        }
    });
  },
  getUserInfo:function(cb){
    var that = this;
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
      console.log('userInfo is in');     
    }else{
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      });
    }
  },
  setPageUserInfo: function(){
    var that =this;
    var session_key;
    if(session_key = wx.getStorageSync('session_key')){
      this.globalData.session_key = session_key;
      wx.checkSession({        
        success: function(res){
          // console.log(res);
          //session 未过期，并且在本生命周期一直有效
        },
        fail: function(){
          //登录态过期
          that.login(); //重新登录
        }
      })
    }else{
      that.globalData.firstlogin = true;
      that.login();
    }
  },
  setPageUserInfo2: function(){
    var that =this;
    wx.login({
        success: function (data) {
          var codes = data.code;
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo;
              var currentPage = that.getCurrentP(),
              newdata = {};
              newdata['userInfo'] = that.globalData.userInfo;
              currentPage.setData(newdata);
            }
          })
        }
    });
  },
  getCurrentP: function(){
    var pages = getCurrentPages();
    return pages[pages.length - 1];
  },
  searchPrdList:function(e){
    var that = this;
    var vendorUserId = this.globalData.vendorUserId;
    var param = wx.getStorageSync('session_key')
    var searchPrdList ={
      token :param.myXcxSessionId,
      source:'1',
      target : '1',  
      userId:param.userId,
      vendorUserId:vendorUserId||'',
      //行业分类 bizCatlg 行业细类 subCatlg 城市 cityId 关键字 keyword 
      bizCatlg:'',
      subCatlg:'',
      cityId:'',
      keyword:'', 
      pageNo:0,
      pageSize:'',    
    }
    that.sendRequest({
      url:'/prod/searchPrdList',
      data:searchPrdList,
      method:'POST',
      success: function(res){
        var data = res.userdata,
        pageN = res.page;
        if(res.records===0){
          that.showToast({
              title: '没有找到产品',
              icon: 'loading'
            });
            }
        var arr = [];
        for(var i=0,len=data.length;i<len;i++){
          var dataset = {}
          var coverImg = data[i].coverImg  
          dataset.content= coverImg;
          // dataset.product_name=data[i].productName;
          dataset.company_name=data[i].productName;
          dataset.eventParams=[data[i].productId,data[0].companyId];
          dataset.eventHandler='tapInnerLinkHandler'
          arr.push(dataset);
        }
        var currentPage = that.getCurrentP();          
        currentPage.setData({
           free_vessel4:{"content":arr,'pageNo':0} 
        })
      },
      fail: function(res){
        console.log('getmode fail');
      },
      complete: function(res){
      }
    })
  },
   requestList:function(){
    var that = this;
    var currentPage = that.getCurrentP();  
    var param =  wx.getStorageSync('session_key')
    var shareToday ={
      token :param.myXcxSessionId,
      source:'1', 
      userId:param.userId 
    }
    that.sendRequest({
      url:'/cust/getShareToday',
      data:shareToday,
      method:'POST',
      success: function(res){
        var data = res;
        data.id = ['2',data.linkId],
        data.eventHandler='banner_event';
        currentPage.setData({
           shareToday: data
        })   
      }
    }) 
    that.sendRequest({
      url:'/cust/getHomeBanner',
      data:shareToday,
      method:'POST',
      success: function(res){
        var data = res.userdata;
        var arr=[];
        for(var i=0,len=data.length;i<len;i++){
          var dataset = {}
          dataset.imgpath = data[i].imgpath;
          dataset.link = data[i].link ;
          dataset.id=['1',data[i].id];
          dataset.sort=data[i].sort;
          dataset.eventHandler='banner_event'
          arr.push(dataset);
        }                  
        currentPage.setData({
           imgUrls: arr
        })     
      }     
    }) 
    that.sendRequest({
      url:'/cust/checkMyMessage',
      data:shareToday,
      method:'POST',
      success: function(res){
        var unreadMsgCount = res.unreadMsgCount;
        if(unreadMsgCount!=0){
          currentPage.setData({
           unreadMsgCount: true
          }) 
        }     
      }     
    })  
  },
  productList: function(e){
    var that = this;
    var param =  wx.getStorageSync('session_key');
    var currentPage = that.getCurrentP(); 
    var prodDetail = {
      source : '1',
      userId : param.userId,
      prodId : e,
      token:param.myXcxSessionId
    }
    that.sendRequest({
      url:'/prod/prodDetail',
      data:prodDetail,
      method:'POST',
      success: function(res){
        if(res.result == 0){
          var navItems=[
            {name:'行业分类:',detail:res.bizCatlgName+'-'+res.subCatlgName||'',url:[res.bizCatlg,res.subCatlgId]},
            {name:'品牌名:', detail:res.brand||'',url:'brand' },
            {name:'规格:',detail:res.spec||'',url:'type'},
            {name:'单位：',detail:res.unit||'',url:'unit',},
            {name:'价格：', detail:'¥'+res.wholesalePrice||'',price:'¥'+res.salesPrice||'' },
            {name:'产品描述：', detail:res.remarks||'', url:'detail',isSplot:true}
            ]          
          var company=[{company_name:res.companyName,companyId:res.companyId,brandId:res.brandId,product_name:res.productName,prodId:e.prodId,product_video:res.prodVideos.video||'',coverImg:res.coverImg,collectedSign:res.collectedSign,mobileNo:res.mobileNo}]
          var imgUrls=[];
          var img = res.productImgs;
          for(var i=0,len=img.length;i<len;i++){if(img[i].img){imgUrls.push(img[i].img)}}
          currentPage.setData({
            wxcode:res.qrCode,
            imgUrls:imgUrls,
            navItems:navItems,
            company:company
          })
         
       }else{
       }
        console.log(res)
      },     
    })
   
  },
  companyList:function(e){
    var that = this;
    var param =  wx.getStorageSync('session_key');
    var currentPage = that.getCurrentP(); 
    var companyDetail = {
      source : '1',
      userId : param.userId,
      companyId : e,
      token:param.myXcxSessionId
    }
    that.sendRequest({
      url:'/company/companyDetail',
      data:companyDetail,
      method:'POST', 
      success: function(res){
        if(res.result == 0){
          res.vendorCatlg=res.vendorCatlg=='I'?'个人':'公司';    
          var company={
            logo:res.companyLogo,
            name:res.companyName,
            site:res.companySite,
            mobileNo:res.mobileNo,
            person:res.contactPerson,
            tel:res.contactTel,
            brief:res.companyBrief,
            c:res.vendorCatlg,
            companyId:e.companyId,
            collectedSign:res.collectedSign||0
          }
          currentPage.setData({
            company:company
          })
        }else{//提示无数据并navigateback
       }
      },
      fail: function(res){
        console.log('getcompany fail');
      },
      complete: function(res){
      }
    })
  },
  getAppId: function(){
    return this.globalData.appId;
  },
  getDefaultPhoto: function(){
    return this.globalData.defaultPhoto;
  },
  setUserInfoStorage: function(info){
    this.globalData.userInfo = info;
    wx.setStorage({
      key: 'userInfo',
      data: this.globalData.userInfo
    })
  },
  checkLogin: function(){
    if(!this.getSessionKey()){
      this.sendSessionKey();
    } else {
      this.login();
    }
  },
  sendCode: function(code){
    var that = this;
    var url = '/login/loginBcXcx';
    this.sendRequest({
      url:url,
      data:code,
      method:'POST',
      success: function(res){
        if(res.resultCode == 0) {
          var session_key={};
          session_key.myXcxSessionId = res.myXcxSessionId;
          session_key.userId = res.userId;
          session_key.qiniuUpURL = res.qiniuUpURL;
          session_key.qiniuDownURL = res.qiniuDownURL;
          session_key.qiniuFileUrl   = res.qiniuFileUrl;
         wx.setStorageSync('session_key', session_key);
         that.globalData.session_key = session_key;
         var currentPage = that.getCurrentP();
         if(currentPage.page_router=='page10000'){
          that.searchPrdList();
          that.requestList();
         }else if(currentPage.page_router=='productdetail'){
          that.productList(that.globalData.prodId);
         }else if(currentPage.page_router=='companydetail'){
          that.companyList(that.globalData.companyId);
         }
        }else{
         // console.log(resultMsg)
        }
      },
      fail: function(res){
        console.log('sendCode fail');
      },
      complete: function(res){
      }
    })
  }, 
  getSessionKey: function(){
    return this.globalData.sessionKey;
  },
  setSessionKey: function(session_key){
    this.globalData.sessionKey = session_key;
    wx.setStorage({
      key: 'session_key',
      data: session_key
    })
  },
  sendSessionKey: function(){
    var that = this;
    try {
      var key = wx.getStorageSync('session_key');
    } catch(e) {

    }

    if (!key) {
      console.log("check login key=====");
      this.login();
//确认登录态
    } else {
      this.globalData.sessionKey = key;
      this.sendRequest({
        method:'POST',
        url: 'getUserinfo',
        success: function(res){
          if(res.code == 400){
            //console.log(res.code)
            // 如果没有登录
            that.login();
            //return;
          } else if(res.code == 200) {
             that.requestUserInfo(1);
              console.log(res.code);
          }      
        },
        fail: function(res){
          console.log('sendSessionKey fail');
        }
      });
    }
  },
  // 向wx服务器check
  sendSessionKeywx: function(){
    var that = this;
    try {
      var key = wx.getStorageSync('session_key');
    } catch(e) {

    }

    if (!key) {
      console.log("check login key=====");
      this.login();

    } else {
      this.globalData.sessionKey = key;
      wx.checkSession({
        success: function(res){   
         console.log('checkLogin success');       
        },
        fail: function(res){
          that.login();
          console.log('checkLogin fail');
        }
      });
    }
  },
  requestUserInfo: function(is_login){
    if(is_login==1){
      this.requestUserXcxInfo();
    } else {
      this.requestUserWxInfo();
    }
  },
  requestUserXcxInfo: function(){
    var that = this;
    this.sendRequest({
      method:'POST',
      url: 'getUserInfo',
      success: function(res){
          if(res.data){
            that.setUserInfoStorage(res.data);
          }
      },
      fail: function(res){
        console.log('requestUserXcxInfo fail');
      }
    })
  },
  requestUserWxInfo: function(){
    var that = this;
    wx.getUserInfo({
      success: function(res){
        that.sendUserInfo(res);
      },
      fail: function(res){
        console.log('requestUserWxInfo fail');
      }
    })
  },
  sendUserInfo: function(res){
    var that = this;
    this.sendRequest({
      url: 'updateUserInfo',
      method: 'POST',
      data: {
        encryptedData: res['encryptedData'],
        iv: res['iv'],
      },
      success: function(res){
        if(res.code == 200){
          that.setUserInfoStorage(res.data);
        }
      },
      fail: function(res){
        console.log('requestUserXcxInfo fail');
      }
    })
  },
  modifyPostParam: function(obj) {
    let query = '',
        name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i < value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += this.modifyPostParam(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += this.modifyPostParam(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  },
  turnToPage: function(url, isRedirect){
    if(!isRedirect){
      wx.navigateTo({
        url: url
      });
    } else {
      wx.redirectTo({
        url: url
      });
    }
  },
  switchToTab: function(url){
    wx.switchTab({
      url: url
    });
  },
  turnBack: function(){
    wx.navigateBack();
  },
  setPageTitle: function(title){
    wx.setNavigationBarTitle({
      title: title
    });
  },
  showToast: function(param){
    wx.showToast({
      title: param.title,
      icon: param.icon,
      duration: param.duration || 1000,
      success: function(res){
        typeof param.success == 'function' && param.success(res);
      },
      fail: function(res){
        typeof param.fail == 'function' && param.fail(res);
      },
      complete: function(res){
        typeof param.complete == 'function' && param.complete(res);
      }
    })
  },
  hideToast: function(){
    wx.hideToast();
  },
  showModal: function(param){
    wx.showModal({
      title: param.title || '提示',
      content: param.content,
      showCancel: param.showCancel || false,
      cancelText: param.cancelText || '取消',
      cancelColor: param.cancelColor || '#000000',
      confirmText: param.confirmText || '确定',
      confirmColor: param.confirmColor || '#3CC51F',
      success: function(res) {
        if (res.confirm) {
          typeof param.confirm == 'function' && param.confirm(res);
        } else {
          typeof param.cancel == 'function' && param.cancel(res);
        }
      },
      fail: function(res){
        typeof param.fail == 'function' && param.fail(res);
      },
      complete: function(res){
        typeof param.complete == 'function' && param.complete(res);
      }
    })
  },
  chooseVideo: function(callback, maxDuration){
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: maxDuration || 60,
      camera: ['front', 'back'],
      success: function (res) {
        typeof callback == 'function' && callback(res.tempFilePaths[0]);
      }
    })
  },
  chooseImage: function(callback, count){
    var that = this;
    wx.chooseImage({
      count: count || 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths,
            imageUrls = [];

        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url : that.globalData.siteBaseUrl+ 'add_img',
            filePath: tempFilePaths[i],
            name: 'img_data',
            success: function(res){
              var data = JSON.parse(res.data);
              if(data.status == 0){
                imageUrls.push(data.data);
                if(imageUrls.length == tempFilePaths.length){
                  typeof callback == 'function' && callback(imageUrls);
                }
              } else {
                that.showModal({
                  content: data.data
                })
              }
            },
            fail: function(res){
              console.log(res.errMsg);
            }
          })
        }

      }
    })
  },
  previewImage: function(previewUrl, previewUrlsArray){
    wx.previewImage({
      current: previewUrl,
      urls: previewUrlsArray
    })
  },
  playVoice: function(filePath){
    wx.playVoice({
      filePath: filePath
    });
  },
  pauseVoice: function(){
    wx.pauseVoice();
  },
  wxPay: function(param){
    var _this = this;
    wx.requestPayment({
      'timeStamp': param.timeStamp,
      'nonceStr': param.nonceStr,
      'package': param.package,
      'signType': 'MD5',
      'paySign': param.paySign,
      success: function(res){
        typeof param.success === 'function' && param.success();
        _this.wxPaySuccess(param);
      },
      fail: function(res){
        if(res.errMsg === 'requestPayment:fail cancel'){
          return;
        }
        _this.showModal({
          content: res.errMsg
        })
        _this.wxPayFail(param, res.errMsg);
      }
    })
  },
  wxPaySuccess: function(param){
    var orderId = param.orderId,
        goodsType = param.goodsType,
        formId = param.package.substr(10),
        t_num = goodsType == 1 ? 'AT0104':'AT0009';

    this.sendRequest({
      url: '/index.php?r=AppShop/SendXcxOrderCompleteMsg',
      data: {
        formId: formId,
        t_num: t_num,
        order_id: orderId
      }
    })
  },
  wxPayFail: function(param, errMsg){
    var orderId = param.orderId,
        formId = param.package.substr(10);

    this.sendRequest({
      url: '/index.php?r=AppShop/SendXcxOrderCompleteMsg',
      data: {
        formId: formId,
        t_num: 'AT0010',
        order_id: orderId,
        fail_reason: errMsg
      }
    })
  },
  // 拨打电话
  makePhoneCall: function(number, callback){
    if(number.currentTarget){
      var dataset = number.currentTarget.dataset;
      number = dataset.number;
    }
    wx.makePhoneCall({
      phoneNumber: number,
      success: callback
    })
  },
  globalData:{
    firstlogin:false,
    defaultPhoto:1,
    vendorUserId:'',
    sessionKey: '',
    page10000_inital:false,
    appId:'wx56528f05208a7861',
    userInfo:null,
    siteBaseUrl:'https://bc.zhaojx.net/bizcat/webservice/rest',
    photo_line:[],
    // 判断是提交后的页面还是查看页面
    newFound:true,
    /**
     * 判断是新增还是修改
     */
    change_param:false,
    change_ca:'',
    change_com:'',
    music:'defalut',
  }
})

